package com.glamour.hlcity.component.log.filter;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.spi.Filter;
import org.apache.log4j.spi.LoggingEvent;

import com.glamour.hlcity.common.exception.BizException;

public class BizExceptionFilter extends Filter {
	private static final String SEPARATOR = ","; // 异常码分割符
	private List<String> errorCodes; // 异常码

	public void setErrorCodes(String errorCodes) {
		String[] codes = errorCodes.split(SEPARATOR);
		this.errorCodes = new ArrayList<String>(codes.length);
		for (String code : codes) {
			this.errorCodes.add(StringUtils.strip(code));
		}
	}

	public String getErrorCodes() {
		return StringUtils.join(errorCodes.iterator(), SEPARATOR);
	}

	public int decide(LoggingEvent event) {
		// 没有配置异常码、没有在抛出异常时指定异常码或异常不是BizException则由后续Filter决定
		if (errorCodes == null
				|| errorCodes.isEmpty()
				|| event.getThrowableInformation() == null
				|| !BizException.class.isAssignableFrom(event
						.getThrowableInformation().getThrowable().getClass())) {
			return Filter.NEUTRAL;
		}
		// 抛出的异常码不是指定异常码范围内的则拒绝
		BizException exception = (BizException) event.getThrowableInformation()
				.getThrowable();
		if (errorCodes.contains(exception.getErrorCode())) {
			//在这里可以加上报警业务
			return Filter.ACCEPT;
		} else {
			return Filter.DENY;
		}
	}

}
